package pers.yurwisher.rubick.gateway.filters;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.rewrite.CachedBodyOutputMessage;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.BodyInserterContext;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import pers.yurwisher.rubick.gateway.filters.AbstractGateWayFilter;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;

/**
 * 日志过滤器，用于记录日志
 *
 * @author yq
 * @date 2021年4月13日 17:17:49
 */
@Slf4j
//@Component
@Deprecated
public class RequestLogFilter extends AbstractGateWayFilter {

    private final ServerCodecConfigurer codecConfigurer;

    public RequestLogFilter(ServerCodecConfigurer codecConfigurer) {
        this.codecConfigurer = codecConfigurer;
    }

    @Override
    public int getOrder() {
        return -100;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest serverHttpRequest = exchange.getRequest();

        String requestId = serverHttpRequest.getId();
        long startTime = System.currentTimeMillis();
        MediaType mediaType = serverHttpRequest.getHeaders().getContentType();
        URI uri = serverHttpRequest.getURI();


        HttpMethod httpMethod = serverHttpRequest.getMethod();

        //打印请求日志 请求ID IP routeId requestPath requestMethod contentType queryParams
        log.info("[{}] [{}] [{}] [{}] [{}] [{}] [{}]",
                requestId,
                this.getIp(serverHttpRequest),
                this.getGatewayRouteId(exchange),
                this.getPath(uri),
                httpMethod,
                mediaType != null ? mediaType.toString() : "",
                this.getQuery(uri));
        if (HttpMethod.POST == httpMethod) {
            // 表单提交 或 json
            if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(mediaType) || MediaType.APPLICATION_JSON.isCompatibleWith(mediaType)) {
                return writeBodyLog(startTime, requestId, exchange, chain);
            }
        }
        return writeBasicLog(startTime, requestId, exchange, chain);
    }

    private Mono<Void> writeBasicLog(long startTime, String requestId, ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取响应体
        ServerHttpResponseDecorator decoratedResponse = recordResponseLog(requestId, exchange);

        return chain.filter(exchange.mutate().response(decoratedResponse).build())
                .then(Mono.fromRunnable(() ->
                        log.info("[{}] 执行时间:[{}]", requestId, System.currentTimeMillis() - startTime)
                ));
    }


    /**
     * 解决 request body 只能读取一次问题，
     * 参考: org.springframework.cloud.gateway.filter.factory.rewrite.ModifyRequestBodyGatewayFilterFactory
     *
     * @param startTime 请求开始时间
     * @param requestId 请求ID
     * @param exchange  exchange
     * @param chain     chain
     * @return
     */
    @SuppressWarnings("unchecked")
    private Mono writeBodyLog(long startTime, String requestId, ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerRequest serverRequest = ServerRequest.create(exchange, codecConfigurer.getReaders());

        Mono<String> modifiedBody = serverRequest.bodyToMono(String.class)
                .flatMap(body -> {
                    log.info("[{}] requestBody:[{}]", requestId, body);
                    return Mono.just(body);
                });

        // 通过 BodyInserter 插入 body(支持修改body), 避免 request body 只能获取一次
        BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody, String.class);
        HttpHeaders headers = new HttpHeaders();
        headers.putAll(exchange.getRequest().getHeaders());
        // the new content type will be computed by bodyInserter
        // and then set in the request decorator
        headers.remove(HttpHeaders.CONTENT_LENGTH);

        CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(exchange, headers);

        return bodyInserter.insert(outputMessage, new BodyInserterContext())
                .then(Mono.defer(() -> {
//                    log.info("[{}] 读取请求体后重新封装请求", requestId);
                    // 重新封装请求
                    ServerHttpRequest decoratedRequest = requestDecorate(exchange, headers, outputMessage);

                    // 记录响应日志
                    ServerHttpResponseDecorator decoratedResponse = recordResponseLog(requestId, exchange);

                    // 记录普通的
                    return chain.filter(exchange.mutate().request(decoratedRequest).response(decoratedResponse).build())
                            .then(Mono.fromRunnable(() -> log.info("[{}] 执行完毕, 执行时间:[{}]", requestId, System.currentTimeMillis() - startTime)));
                }));
    }

    /**
     * 获取route Id
     *
     * @param exchange
     * @return route id
     */
    private String getGatewayRouteId(ServerWebExchange exchange) {
        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        return route != null ? route.getId() : "";
    }


    /**
     * 获取IP
     */
    private String getIp(ServerHttpRequest serverHttpRequest) {
        InetSocketAddress address = serverHttpRequest.getRemoteAddress();
        if (address != null) {
            InetAddress inetAddress = address.getAddress();
            if (inetAddress != null) {
                return inetAddress.getHostAddress();
            }
        }
        return null;
    }

    /**
     * 请求路径 如/nacos
     */
    private String getPath(URI uri) {
        return uri != null ? uri.getPath() : null;
    }

    /**
     * 获取url请求参数 形如 a=1&b=2
     */
    private String getQuery(URI uri) {
        return uri != null ? uri.getQuery() : "";
    }


    /**
     * 请求装饰器，重新计算 headers
     *
     * @param exchange
     * @param headers
     * @param outputMessage
     * @return
     */
    private ServerHttpRequestDecorator requestDecorate(ServerWebExchange exchange, HttpHeaders headers,
                                                       CachedBodyOutputMessage outputMessage) {
        return new ServerHttpRequestDecorator(exchange.getRequest()) {
            @Override
            public HttpHeaders getHeaders() {
                long contentLength = headers.getContentLength();
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.putAll(super.getHeaders());
                if (contentLength > 0) {
                    httpHeaders.setContentLength(contentLength);
                } else {
                    httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
                }
                return httpHeaders;
            }

            @Override
            public Flux<DataBuffer> getBody() {
                return outputMessage.getBody();
            }
        };
    }


    /**
     * 记录响应日志
     * 通过 DataBufferFactory 解决响应体分段传输问题。
     */
    private ServerHttpResponseDecorator recordResponseLog(String requestId, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        DataBufferFactory bufferFactory = response.bufferFactory();

        return new ServerHttpResponseDecorator(response) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {

                    // 获取响应类型，如果是 json 就打印
                    String originalResponseContentType = exchange.getAttribute(ServerWebExchangeUtils.ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR);

                    if (ObjectUtil.equal(this.getStatusCode(), HttpStatus.OK)
                            && StrUtil.isNotEmpty(originalResponseContentType)
                            && originalResponseContentType.contains("application/json")) {

                        Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                        return super.writeWith(fluxBody.buffer().map(dataBuffers -> {

                            // 合并多个流集合，解决返回体分段传输
                            DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                            DataBuffer join = dataBufferFactory.join(dataBuffers);
                            byte[] content = new byte[join.readableByteCount()];
                            join.read(content);

                            // 释放掉内存
                            DataBufferUtils.release(join);
                            String responseResult = new String(content, StandardCharsets.UTF_8);

                            log.info("[{}] responseBody:[{}]", requestId, responseResult);

                            return bufferFactory.wrap(content);
                        }));
                    }
                }
                // if body is not a flux. never got there.
                return super.writeWith(body);
            }
        };
    }

    @Override
    protected boolean ignoreExpress(ServerWebExchange exchange) {
        return false;
    }
}
